<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<el-form-item>
							<el-button v-if="$hasPer('visitorManagement1:add')" @click="addNodeClick" icon="ele-Plus" type="primary"> 上传视频 </el-button>
							<el-button v-if="$hasPer('visitorManagement2:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref="excelRef" :data="list" class="w-h-100" style="width: 100%" border element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
									
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="访客姓名" align="center">
											<el-table-column min-width="140" :show-overflow-tooltip="true" label="访客姓名" align="center">
												<template #header>
													<SearchModel typeId="v_Name" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.v_Name }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="140" :show-overflow-tooltip="true"  label="手机号码" align="center">
											<el-table-column min-width="140" :show-overflow-tooltip="true" label="手机号码" align="center">
												<template #header>
													<SearchModel typeId="mobileNumber" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.mobileNumber }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="visitingCompany" label="单位名称" align="center">
											<template #default="{row}">
												{{ row.visitingCompany ? row.visitingCompany : '-' }}
											</template>
										</el-table-column>
										<!-- <el-table-column min-width="120" :show-overflow-tooltip="true" prop="schemeIdName" label="到访部门" align="center" /> -->
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="travelArea" label="到访区域" align="center">
										   <template #default="{row}">
												{{ row.travelArea ? '车间' : '办公室' }}
											</template>	
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="entourage" label="随行人员" align="center">
											<template #default="{row}">
												{{ row.entourage ? row.entourage : '-' }}
											</template>
										</el-table-column>
										<el-table-column min-width="240" :show-overflow-tooltip="true" label="申请时间" align="center" >
											<el-table-column min-width="240" :show-overflow-tooltip="true"  label="申请时间" align="center">
												<template #header>
													<SearchModel typeId="d_ApplyTime" typeVal="datetime" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.d_ApplyTime }}
												</template>
											</el-table-column>
										</el-table-column>

										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="beginTime" label="来访开始时间" :formatter="formatDate" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="endTime" label="来访结束时间" :formatter="formatDate" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="contet" label="具体工作内容" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="clerk" label="接待人员" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="visaTime" label="签证时间" align="center" >
												<template #default="{row}">
														{{ row.visaTime ? row.visaTime : '-' }}
												</template>
										</el-table-column>
										<!-- <el-table-column min-width="120" :show-overflow-tooltip="true" prop="arriveTime" label="进入时间" align="center" >
												<template #default="{row}">
														{{ row.arriveTime ? row.arriveTime : '-' }}
												</template>
										</el-table-column> -->
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="leaveTime" label="离开时间" align="center" >
												<template #default="{row}">
														{{ row.leaveTime ? row.leaveTime : '-' }}
												</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="车牌号" align="center">
											<template #default="scope">
												<span v-if="scope.row.licensePlate">{{ scope.row.licensePlate }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="180" label="操作" align="center" fixed="right">
											<el-table-column min-width="180" fixed="right" align="center">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" class="clear-bg" text> 重置 </el-button>
												</template>
												<template #default="{ row }">
													<div class="operate-s">
														<template v-if="!row.visaId"> 
															<el-button  v-if="$hasPer('visitorManagement8:visa')" @click="editNodeClick(row)" icon="ele-Edit" type="primary" text> 签证 </el-button>
														</template>
														<el-button  v-if="$hasPer('visitorManagement9:file')"  @click="documentClick(row)" icon="DocumentAdd" text type="primary"> 附件管理 </el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" title="新增" width="50%" @close="cancelUseClick">
			<el-form label-width="120px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="n_FlcFlowschemeId" label="流程模板">
							<el-select v-model="ruleForm.n_FlcFlowschemeId" class="m-2" placeholder="请选择流程模板" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="i_Validity" label="观看有效期(月)">
							<el-input-number v-model="ruleForm.i_Validity" :min="1" :max="12" placeholder="请填写观看有效期" style="width: 100%" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-divider content-position="left"> 视频上传 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-upload ref="upload" action="#" v-model:file-list="fileList" :limit="1" :on-change="   (file: any) => { handleChange(file) }" :auto-upload="false">
							<template #trigger>
								<el-button type="primary">选择视频</el-button>
							</template>
							<template #tip>
								<div class="el-upload__tip text-red">请选择mp4格式的视频，且只能上传一个视频，选择视频后确认信息无误后请点击确认按钮保存视频以及相关信息</div>
							</template>
						</el-upload>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 签证 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible1" title="签证" width="50%" @close="cancelUseClick1">
			<el-form label-width="120px" ref="ruleFormRef1" :model="ruleForm1" size="default" :rules="rules1">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="leaveTime" label="离开时间">
							<el-date-picker 	v-model="ruleForm1.leaveTime"
        type="datetime"   placeholder="离开时间"   />
						</el-form-item>
					</el-col> -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="visaTime" label="签证时间">
							<el-date-picker  style="width:100% " v-model="ruleForm1.visaTime" type="datetime"   placeholder="签证时间"  />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick1">取消</el-button>
					<el-button type="primary" @click="controlUseClick1(ruleFormRef1)">确定</el-button>
				</span>
			</template>
		</el-dialog>
			<!-- 文件上传 -->
			<uploadFile isAccept="" :fileInfo="fileInfo" :isUseDialog="fileDialog" @cancelFileClick="cancelFileClick" @controlFileClick="controlFileClick" @updateData="getData" />
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import { ElMessage, ElMessageBox, FormInstance, UploadInstance, dayjs } from 'element-plus';
import { getVisitorApplyListApi, getVisitorVideoApi, updateVisitorEditRuleFormType } from '/@/api/sms/HazardousChemicalsInterface';
import { getProcessTemplateApi } from '/@/api/workFlow';
import { exportToExcel } from '/@/utils/exportToExcel';
import UploadFile from '/@/views/sms/component/reviseUploadFile.vue';
import SearchModel from '/@/views/sms/component/search-model.vue';
const searchObj: any = reactive({
	applyTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
});
//新增
const showDialogVisible = ref(false);
const ruleForm: any = reactive({
	file: '',
	i_Validity: '1',
	n_FlcFlowschemeId: '',
});

/***** searchClick 查询按钮 *****/
const searchClick = () => {
	let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = searInfo.value[i];
		});
	}
};

/***** resetClick 重置按钮 *****/
const resetClick = () => {
	searInfo.value = {};
	let newObj = Object.keys(searchObj);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = '';
		});
	}
	searchObj['applyTime'] = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
	initInfoFun();
};

//编辑
const editNodeClick = (row: any) => {
	console.log(row);
	ruleForm1.n_Id = row.n_Id;
	showDialogVisible1.value = true;
};

const options1 = ref([]);
onMounted(async () => {
	initInfoFun();

	const res = await getProcessTemplateApi({ SchemeTypeCode: 'VistorApplyFlow' });
	options1.value = res.data.map((item: any) => {
		return {
			label: item.schemeName,
			value: item.id,
		};
	});
});

/***** addNodeClick 新增 *****/
const addNodeClick = async () => {
	showDialogVisible.value = true;
};

/*** cancelUseClick  弹窗取消事件 */
const cancelUseClick = () => {
	showDialogVisible.value = false;
	ruleForm.file = '';
	ruleForm.i_Validity = '1';
	ruleForm.n_FlcFlowschemeId = '';
	fileList.value = [];
	upload.value?.clearFiles();
};

/*** controlUseClick  弹窗提交事件 */
const controlUseClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	if (!ruleForm.file.length) return ElMessage.error('请上传视频');
	await formEl.validate((valid, fields) => {
		if (valid) {
			getVisitorVideoApi(ruleForm).then((res) => {
				console.log(res);
				cancelUseClick();
				getData();
			});
		} else {
			console.log('error submit!', fields);
		}
	});
};

/*** ruleFormRef  表单校验 */
const ruleFormRef = ref();
const rules = reactive({
	i_Validity: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' },
	],
	n_FlcFlowschemeId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});

const rules1 = reactive({

	visaTime: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});

//上传视频
const upload = ref<UploadInstance>();
const fileList = ref([]);
const handleChange = (uploadFile: any) => {
	const videoType = uploadFile.name.split('.')[1];
	if (videoType != 'mp4') return ElMessage.error('请上传mp4格式的视频');
	console.log(uploadFile);
	ruleForm.file = [uploadFile.raw];
};

//签证
const showDialogVisible1 = ref(false);
const ruleFormRef1 = ref();
const ruleForm1 = reactive({
	visaId:JSON.parse(localStorage.getItem('userInfoData') || '' ).id || 0,
	visaTime:'',
	visaName:JSON.parse(localStorage.getItem('userInfoData') || '' ).name || '',
	n_Id:0
});
const  cancelUseClick1 = () => {
	showDialogVisible1.value = false;
	ruleForm1.n_Id = 0;
	ruleForm1.visaTime = '';
}
const controlUseClick1 = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			console.log(ruleForm1);
			ruleForm1.visaTime = dayjs(ruleForm1.visaTime).format('YYYY-MM-DD HH:mm:ss');
			updateVisitorEditRuleFormType(ruleForm1).then((res) => {
				console.log(res);
				cancelUseClick1();
				getData();
			});
		} else {
			console.log('error submit!', fields);
		}
	});
};


/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'mobileNumber', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'MobileNumber', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '手机号码', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
		{
			typeId: 'v_Name', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'name', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '访客姓名', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
		{
			typeId: 'd_ApplyTime', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'applyTime', // 查询字段 --- 必填
			defaultVal:   dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'), // 字段默认值 --- 选填
			placeholder: '申请时间', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};
const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};
/*** 截取日期格式方法 */
const formatDate = (row: any, column: any) => {
	// 获取单元格数据
	let data = row[column.property];
	if (data == null) {
		return '-';
	}
	if (data === '1900-01-01 00:00:00') {
		return '-';
	}
	let dt = new Date(data);
	let month = dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1;
	let date = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate();
	return dt.getFullYear() + '-' + month + '-' + date;
};

/*** ================================= 导出数据函数操作 ================================= */
const excelRef: any = ref(null);
const handleExport = () => {
	if (excelRef.value) {
		if (excelRef.value.data.length !== 0) {
			let tableExcel: any = [];
			let tableArr = excelRef.value.data;
			tableArr.map((item: any) => {
				let tableObj: any = {};
				tableObj['姓名'] = item.v_Name ? item.v_Name : '-';
				tableObj['供应商类型'] = item.providerType ? item.providerType : '-';
				tableObj['停车区域'] = item.parkArea ? item.parkArea : '-';
				tableObj['车牌号'] = item.licensePlate ? item.licensePlate : '-';
				tableObj['证件类型'] = item.idType ? item.idType : '-';
				tableObj['身份证号'] = item.mobileNumber ? item.mobileNumber : '-';
				tableObj['来访公司'] = item.visitingCompany ? item.visitingCompany : '-';
				tableObj['申请时间'] = item.d_ApplyTime ? item.d_ApplyTime : '-';
				tableObj['来访开始时间'] = item.beginTime ? item.beginTime : '-';
				tableObj['来访结束时间'] = item.endTime ? item.endTime : '-';
				tableObj['具体工作内容'] = item.contet ? item.contet : '-';
				tableObj['到访区域'] = item.travelArea ? item.travelArea : '-';
				// tableObj['流程模板'] = item.schemeId ? item.schemeId : '-';
				tableObj['接待人员'] = item.clerk ? item.clerk : '-';
				tableObj['是否观看视频'] = item.b_IsWatch ? item.b_IsWatch : '-';
				tableExcel.push(tableObj);
			});
			exportToExcel(tableExcel, '访客申请记录记录.xlsx');
		} else {
			ElMessage({
				type: 'error',
				message: '暂无数据导出',
			});
		}
	}
};

/*** 附件管理 */
const fileInfo = ref();
		const fileDialog = ref(false);
		/*** cancelFileClick 文件上传取消事件 */
		const cancelFileClick = () => {
			fileDialog.value = false;
		};

		/*** controlFileClick 文件上传提交事件 */
		const controlFileClick = () => {
			fileDialog.value = false;
		};

		/*** documentClick 文档上传事件 */
		const documentClick = (val: any) => {
			console.log(val, 'val');
			val.sourceType = 10;
			val.sourceId = val.n_Id;
			val.titleCon = '附件上传';
			fileInfo.value = JSON.stringify(val);
			fileDialog.value = true;
		};



const { handleCurrentChange, pageSize, pageNo, handleSizeChange, totalRows, list, indexMethod, loading, getData } = getTableData(getVisitorApplyListApi, {}, searchObj);
</script>

<style lang="scss">
@import '../../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	:deep(.el-upload--picture-card) {
		--el-upload-picture-card-size: 90px;
		background-color: #cccccc56;
		margin-bottom: 2px;
	}

	:deep(.el-upload-list__item) {
		width: 90px;
		height: 90px;
	}

	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}

	.cardBox {
		margin: 6px;
		width: 100%;
		height: 100%;
		border: 1px solid #ccc;

		.cardOne {
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1px solid #ccc;
			width: 100%;
			height: 40px;

			li {
				display: flex;
				align-items: center;

				&:nth-child(1) {
					display: flex;
					width: 50%;

					span {
						padding: 0 4px;
						width: 70px;
					}

					p {
						flex: 1;
					}
				}

				&:nth-child(2) {
					display: flex;
					width: 50%;

					span {
						padding: 0 4px;
						width: 70px;
					}

					p {
						flex: 1;
					}
				}
			}
		}

		.cardTwo {
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1px solid #ccc;
			width: 100%;
			height: 200px;

			li {
				display: flex;
				align-items: center;

				&:nth-child(1) {
					display: flex;
					width: 50%;

					span {
						padding: 0 4px;
						width: 70px;
					}

					p {
						flex: 1;
					}
				}

				&:nth-child(2) {
					display: flex;
					width: 50%;

					span {
						padding: 0 4px;
						width: 70px;
					}

					p {
						flex: 1;
					}
				}
			}
		}

		.cardThree {
			display: flex;
			justify-content: center;
			align-items: center;
			border-bottom: 1px solid #ccc;
			width: 100%;
			height: 100px;

			p {
				&:nth-child(1) {
					padding: 0 4px;
					width: 70px;
				}

				&:nth-child(2) {
					flex: 1;
					text-align: center;

					.upload-s {
						width: 100%;
						height: 100%;
					}
				}
			}
		}

		.cardFour {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 40px;

			p {
				&:nth-child(1) {
					padding: 0 4px;
					width: 70px;
				}

				&:nth-child(2) {
					flex: 1;
					text-align: center;
				}
			}
		}
	}
}
</style>
